package com.prashantdctm.paidemail;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.gargoylesoftware.htmlunit.util.WebConnectionWrapper;

public class GaeWebClient extends WebClient {
	public static StringBuffer cookieHeader = new StringBuffer();
	public static ArrayList<String> cookieHeaderArr = new ArrayList<String>();
	private static final Logger log = Logger.getLogger(GaeWebClient.class.getName());
	
	public static void main(String[] args) {
		
	}
	
	public GaeWebClient() {
		super();
		cookieHeader = new StringBuffer();
		cookieHeaderArr = new ArrayList<String>();
	}
	
	public GaeWebClient(BrowserVersion bw) {
		super(bw);
		cookieHeader = new StringBuffer();
		cookieHeaderArr = new ArrayList<String>();
	}
	
	public HtmlPage getPage(String url) throws IOException, FailingHttpStatusCodeException, MalformedURLException {
		HtmlPage page = super.getPage(url);
		if(PaidEmailServlet.debugMode==true) {
			//GaeHttpServlet.customLog(page.asXml());
		}
		
		//Extract cookie from Response Headers
		if(PaidEmailServlet.debugMode==true) GaeHttpServlet.customLog("Original Response Headers:");
		for(NameValuePair header : page.getWebResponse().getResponseHeaders()) {
			if(PaidEmailServlet.debugMode==true) GaeHttpServlet.customLog(header.toString());
			if(header.getName().equalsIgnoreCase("Set-Cookie")) {
				String str = header.toString();
				if(!cookieHeaderArr.contains(str)) {
					cookieHeader.append(str.substring(str.indexOf("=")+1)+";");
					cookieHeaderArr.add(str);
				}
			}
		}
		
		// Add the extracted cookies as part of the request header "Cookie"
		String queryString = "";
		for (Cookie c : this.getCookieManager().getCookies()) {
			if(PaidEmailServlet.debugMode==true) GaeHttpServlet.customLog(c.getName() + "=" + c.getValue() + "; ");
			if(!cookieHeaderArr.contains(c.getName())) {
				cookieHeader.append(c.getName() + "=" + c.getValue() + "; ");
				cookieHeaderArr.add(c.getName());
			}
			
		}
		if(PaidEmailServlet.debugMode==true) GaeHttpServlet.customLog("Modified Request Headers: "+cookieHeader.toString());
		this.addRequestHeader("Cookie", cookieHeader.toString());
		
		this.addRequestHeader("WWW-Authenticate", null);
		/*//Extract cookies from response and set in next request
		CookieManager currentManager = this.getCookieManager();
		CookieManager newManager = new CookieManager();

		// Extract the cookies
		final Set<Cookie> cookies = currentManager.getCookies();

		// Remove cookies from CookieManager
		this.setCookieManager(newManager);

		WebConnectionWrapper wb = new WebConnectionWrapper(this) {

			public WebResponse getResponse(WebRequest settings)
					throws IOException {

				// Add the extracted cookies as part of the request header "Cookie"
				String queryString = "";
				for (Cookie c : cookies) {
					queryString = queryString + c.getName() + "="
							+ c.getValue() + "; ";
				}
				GaeHttpServlet.customLog("New header: "+queryString);
				// Set the header
				settings.setAdditionalHeader("Cookie", queryString);

				WebResponse response = (WebResponse) super.getResponse(settings);

				// Debug the response
				List<NameValuePair> list = response.getResponseHeaders();
				for (NameValuePair nv : list) {
					System.out.println("Custom "+nv.getName() + " " + nv.getValue());
				}
				System.out.println();

				return response;
			}
		};
		
		GaeHttpServlet.customLog("cookieHeader: "+cookieHeader.toString());
		this.addRequestHeader("Cookie", cookieHeader.toString());*/
		
		return page;
	}
	

}
